package com.buobao.mybatis.annotationtest;

import com.buobao.mybatis.annotationtest.dao.GoodsDAO;
import com.buobao.mybatis.annotationtest.entity.Goods;
import com.buobao.mybatis.annotationtest.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class MyBatisTestor {
    private static PrintStream out;
    static {
        try {
            out = new PrintStream(System.out, true, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void testSelectByRange() {
        SqlSession sqlSession = null;

        try{
            sqlSession = MyBatisUtils.openSession();
            GoodsDAO goodsDAO = sqlSession.getMapper(GoodsDAO.class);
            List<Goods> list = goodsDAO.selectByPriceRange(100f,500f,20);
            list.stream().forEach(s->out.println(s));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }

    @Test
    public void testInsert() {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            Goods goods = new Goods();
            goods.setTitle("this is my inset goods");
            goods.setSubTitle("this is inserted goods' subtitle");
            goods.setOriginalCost(200f);
            goods.setDiscount(50f);
            goods.setCurrentPrice(150f);
            goods.setFreeDelivery(1);
            goods.setCategoryId(43);
            GoodsDAO dao = sqlSession.getMapper(GoodsDAO.class);
            int result = dao.insert(goods);
            out.println("result:"+result);
            out.println(goods.getGoodsId());
            sqlSession.commit();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }
}
